<?php
/**
 * @since   2022-02-20
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */


declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Middleware\AdminMiddleware;
use App\Model\AdminApp;
use App\Model\AdminList;
use App\Service\ToolService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use function Hyperf\Config\config;


#[Controller(prefix: '/admin/App'), Middleware(AdminMiddleware::class)]
class AppController extends BaseController {

    #[GetMapping(path: 'index')]
    public function index(): array {
        $limit    = $this->request->query('size', config('apiadmin.admin_list_default'));
        $keywords = $this->request->query('keywords', '');
        $type     = $this->request->query('type', '');
        $status   = $this->request->query('status', '');

        $obj = AdminApp::query();
        if (strlen($status)) {
            $obj = $obj->where('app_status', $status);
        }
        if ($type) {
            switch ($type) {
                case 1:
                    $obj = $obj->where('app_id', $keywords);
                    break;
                case 2:
                    $obj = $obj->where('app_name', 'like', "%{$keywords}%");
                    break;
            }
        }
        $listObj = $obj->orderByDesc('app_add_time')->paginate((int)$limit);

        return $this->buildSuccess([
            'list'  => $listObj->items(),
            'count' => $listObj->total()
        ]);
    }

    #[GetMapping(path: 'getAppInfo')]
    public function getAppInfo(): array {
        $apiArr = AdminList::query()->get();

        $res['apiList'] = [];
        foreach ($apiArr as $api) {
            $res['apiList'][] = $api;
        }

        $id = $this->request->query('id', 0);
        if (empty($id)) {
            $res['app_id']     = random_int(1, 9) . ToolService::randString(7, 1);
            $res['app_secret'] = ToolService::randString(32);
        }

        return $this->buildSuccess($res);
    }

    #[GetMapping(path: 'refreshAppSecret')]
    public function refreshAppSecret(): array {
        $data['app_secret'] = ToolService::randString(32);

        return $this->buildSuccess($data);
    }

    #[PostMapping(path: 'add')]
    public function add(): array {
        $postData = $this->request->post();
        $data     = [
            'app_id'       => $postData['app_id'],
            'app_secret'   => $postData['app_secret'],
            'app_name'     => $postData['app_name'],
            'app_info'     => $postData['app_info'],
            'app_add_time' => time(),
            'app_api'      => ''
        ];
        if (isset($postData['app_api']) && $postData['app_api']) {
            $appApi = [];
            foreach ($postData['app_api'] as $value) {
                $appApi = array_merge($appApi, $value);
            }
            $data['app_api'] = implode(',', $appApi);
        }
        $res = AdminApp::insert($data);
        if ($res === false) {
            return $this->buildFailed(ErrorCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    #[GetMapping(path: 'changeStatus')]
    public function changeStatus(): array {
        $id     = $this->request->query('id');
        $status = $this->request->query('status');

        $appInfo             = AdminApp::query()->where('id', $id)->first();
        $appInfo->app_status = $status;
        $appInfo->save();

        return $this->buildSuccess();
    }

    /**
     * 编辑应用
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'edit')]
    public function edit(): array {
        $postData = $this->request->post();
        $data     = [
            'app_secret' => $postData['app_secret'],
            'app_name'   => $postData['app_name'],
            'app_info'   => $postData['app_info'],
            'app_api'    => ''
        ];
        if (isset($postData['app_api']) && $postData['app_api']) {
            $appApi = [];
            foreach ($postData['app_api'] as $value) {
                $appApi = array_merge($appApi, $value);
            }
            $data['app_api'] = implode(',', $appApi);
        }
        AdminApp::query()->where('id', $postData['id'])->update($data);

        return $this->buildSuccess();
    }

    /**
     * 删除应用
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $id = $this->request->query('id');
        if (!$id) {
            return $this->buildFailed(ErrorCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminApp::destroy($id);

        return $this->buildSuccess();
    }
}

